<?php
namespace src\logic;
use classlib\acl;
use \classlib\core as C;
class lanalysis_log {
	const COLLECT_GAME_ID 		  = '1994019904';//游戏ID
	const TRACK_APP_SERVER_URL    = '//www.igg.com/';//应用服务器URL，URL以斜杠/结尾
	const TIME_ZONE     		  = 'GMT-5';//如GMT+8 , GMT-5等
	const COLLECT_ADDRESS 		  = '//collect.snd.igg.com/thirdparty_callback.php';//收集地址
	const INVITE_TYPE_ALL         = 0;//不区分推荐类型
	const INVITE_TYPE_FROM_FRIEND = 1;//好友邀请
	const INVITE_TYPE_FROM_PRESENT= 2;//礼品赠送
	const INVITE_TYPE_FROM_FEED   = 3;//feed事件通知
	const CAD2USDRATIO 			  = 0.7751;//汇率
	const PAYCURRENCY			  = 'CAD'; //币种
	const COLLECT_INSTALL_ADDRESS = '//collect.snd.igg.com/thirdparty_install_callback.php';
	
	//存放全局的入口位置
	public static function init() {
		if(isset($_GET['cid'])) {
			$_GET['cid'] = intval($_GET['cid']);
			setcookie('cid', $_GET['cid'], 0, '/');
		}
		if(isset($_GET['kid'])){
			$_GET['kid'] = intval($_GET['kid']);
			setcookie('kid', $_GET['kid'], 0, '/');
		}
		if(isset($_GET['key'])){
			$_GET['key'] = trim($_GET['key']);
			setcookie('key', $_GET['key'], 0, '/');
		}
		setcookie('isnew', null, C\config::$nowtime - 86400, '/');
	}
	
	//fb像素的广告链接
	public static function ad_fb_pix() {
		$isnew = isset($_COOKIE['isnew'])? intval($_COOKIE['isnew']):0;
		if ($isnew) {
			setcookie('isnew', null, C\config::$nowtime - 86400, '/');
			return "fbq('track', 'CompleteRegistration');";
		}
		return '';
	}
	
	/**
	 * 记录广告跟踪数据 (放在游戏首页调用)
	 * @@param integer $iggid IGG ID
	 * @param string $code 直接输出数据或返回数据
	 */
	public static function ad_track_log() {
		$acl = acl::inst('ACLweb');
		$cid = isset($_COOKIE['cid'])? intval($_COOKIE['cid']):0;
		if (!$cid) {//渠道信息不需要跟踪处理
			return $code;
		}
		$kid = isset($_COOKIE['kid'])? intval($_COOKIE['kid']):'';
		$key = isset($_COOKIE['key'])? trim($_COOKIE['key']):'';
		//记录匿名用户跟踪
		$cidkey = isset($_COOKIE['cidkidkey'])? $_COOKIE['cidkidkey']:'';
		$cookie = $cid.$kid.$key;
		$code   = '';
		if ($cookie != $cidkey) {
			setcookie('cidkidkey', $cookie);
			$id    = isset($_COOKIE['sed'])? $_COOKIE['sed']:$cookie;
			$code  = '<iframe src="'.self::COLLECT_INSTALL_ADDRESS.'?'
				.'gid='.self::COLLECT_GAME_ID.'&id='.$id.'&cid='.$cid.'&kid='.$kid.'&key='.$key
				.'" frameborder="0" width="0" height="0"></iframe>';
			$code .= "\n".'<script type="text/javascript">';
			$code .= "\n".'if(typeof(TrackLog) != "undefined" && typeof(TrackLog.C_AD_LOG) != "undefined"){';
			$code .= "\n TrackLog.write(TrackLog.C_AD_LOG); //记录广告跟踪";
			$code .= "\n"."}";
			$code .= "\n".'</script>';
		}
		//记录广告点击登录跟踪
		$isnew = isset($_COOKIE['isnew'])? intval($_COOKIE['isnew']):0;
		if (!$isnew || !$acl->islogin()) {
			return $code;
		}
		setcookie('cid', null, config::$nowtime - 86400, '/');
		setcookie('kid', null, config::$nowtime - 86400, '/');
		setcookie('key', null, config::$nowtime - 86400, '/');
		setcookie('isnew', null, config::$nowtime - 86400, '/');
		$code .= '<iframe src="'.self::COLLECT_ADDRESS.'?'.'gid='.self::COLLECT_GAME_ID.
			'&iggid='.$acl->user['id'].'&cid='.$cid.'&kid='.$kid.'&key='.$key.'" frameborder="0" width="0" height="0"></iframe>';
		$code .= "\n".'<script type="text/javascript">';
		$code .= "\n".'if(typeof(TrackLog) != "undefined" && typeof(TrackLog.C_AD_LOG) != "undefined"){';
		$code .= "\n TrackLog.write(TrackLog.C_AD_LOG); //记录广告跟踪";
		$code .= "\n"."}";
		$code .= "\n".'</script>';
		$code .= '<!-- Google Code for Pocket Live Web Install Conversion Page -->
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 874266110;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "DSPlCNOs-2kQ_vvwoAM";
var google_remarketing_only = false;
/* ]]> */
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/conversion/874266110/?label=DSPlCNOs-2kQ_vvwoAM&amp;guid=ON&amp;script=0"/>
</div>
</noscript>';
		return $code;
	}
	
	//创建数据库连接，已经连接了直接返回句柄
	private static function __dbconn__() {
		$dbh = null;
		try {
			$db  = C\config::load('db/gamelog', false);
			$dbh = new \PDO($db['writer']['params']['dsn'], $db['writer']['params']['user'],
				$db['writer']['params']['password'], $db['writer']['options']);
		} catch (\PDOException $e) {
			\classlib\logger::inst()->write($e->getMessage());
		}
		return $dbh;	
	}
	
	/**
	 * 添加登录日志资料信息
	 * @param int $userid
	 * @param string $ip
	 * @param int $stime
	 */
	public static function add_login_log($userid, $ip, $stime) {
		$dbh = self::__dbconn__();
		$mac = '';
		if ($dbh) {
			$stmt = $dbh->prepare("CALL sp_add_login_log(:gameid, :uin, :logip, :mac, :logtime);");
			$stmt->bindValue(':gameid', self::COLLECT_GAME_ID);
			$stmt->bindValue(':uin', $userid);
			$stmt->bindValue(':logip', $ip);
			$stmt->bindValue(':mac', $mac);
			$stmt->bindValue(':logtime', date('Y-m-d H:i:s', $stime));
			$stmt->execute();
			$stmt->closeCursor();
			$dbh = null;
		}
	}
	
	/**
	 * 添加充值跟踪日志信息
	 * @param array $order
	 */
	public static function add_payment_log($user, $order) {
		$dbh = self::__dbconn__();
		if ($dbh) {
			$sql = 'insert into t_order(o_serialnum, g_id, s_id, m_id, m_name, m_country, pm_id, pc_id, o_credit,'.
				' o_addmethod, o_pay_acc, o_quantity, o_unitpoint, o_point, o_free_point, o_unitprice, o_price, o_price_usd,'.
				' o_cointype, o_ip, o_country, o_memo, o_status, o_create_time, o_edit_time)'.
				' values(:o_serialnum, :g_id, :s_id, :m_id, :m_name, :m_country, :pm_id, :pc_id, :o_credit,'.
				' :o_addmethod, :o_pay_acc, :o_quantity, :o_unitpoint, :o_point, :o_free_point, :o_unitprice, :o_price, :o_price_usd,'.
				' :o_cointype, :o_ip, :o_country, :o_memo, :o_status, :o_create_time, :o_edit_time)';
			
			$stmt     = $dbh->prepare($sql);
			$moeny    = sprintf('%.03f', $order['money']/100.00);
			$usdmoney = sprintf('%.03f', $moeny * self::CAD2USDRATIO);
			$country  = \classlib\iplocation::country();
			$stmt->bindValue(':o_serialnum', $order['paysn']);
			$stmt->bindValue(':g_id', self::COLLECT_GAME_ID);
			$stmt->bindValue(':s_id', 0);
			$stmt->bindValue(':m_id', $order['userid']);
			$stmt->bindValue(':m_name', substr($user['nickname'], 0, 20));//昵称最多取20个字符
			$stmt->bindValue(':m_country', $country);
			$stmt->bindValue(':pm_id', $order['payorigin']);
			$stmt->bindValue(':pc_id', $order['payconfid']);
			$stmt->bindValue(':o_credit', 0);
			$stmt->bindValue(':o_addmethod', 0);
			$stmt->bindValue(':o_pay_acc', $order['payaccount']);
			$stmt->bindValue(':o_quantity', 1);
			$stmt->bindValue(':o_unitpoint', $order['coin']);
			$stmt->bindValue(':o_point', $order['coin']);
			$stmt->bindValue(':o_free_point', 0);
			$stmt->bindValue(':o_unitprice', $moeny);
			$stmt->bindValue(':o_price', $moeny);
			$stmt->bindValue(':o_price_usd', $usdmoney);
			$stmt->bindValue(':o_cointype', self::PAYCURRENCY);
			$stmt->bindValue(':o_memo', $order['memo']);
			$stmt->bindValue(':o_ip', $order['ip']);
			$stmt->bindValue(':o_country', $country);
			$stmt->bindValue(':o_status', 1);
			$stmt->bindValue(':o_create_time', $order['addtime']);
			$stmt->bindValue(':o_edit_time', $order['paytime']);
			$stmt->execute();
			$stmt->closeCursor();
			$dbh = null;
		}
	}
}